package com.deng.commons.utils;

import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * 用户工具类
 */
public class UserUtils {

    /**
     * 用户的认证信息存放到SecurityContext中，我们需要从这里面获取
     * @return
     */
    public static UserDetails getUser(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //匿名用户
        if ( authentication instanceof AnonymousAuthenticationToken){
            throw new RuntimeException("没有这个用户 ！");
        }else{
            UserDetails user = (UserDetails) authentication.getPrincipal();
            return user;
        }
    }

}
